package com.baijiayun.liveuibase.toolbox.bonuspoints

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Typeface
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.liveuibase.R
import com.baijiayun.liveuibase.base.BaseUIConstant
import com.baijiayun.liveuibase.base.BaseWindow
import com.baijiayun.liveuibase.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder
import com.baijiayun.liveuibase.utils.drawable.StateListDrawableBuilder
import com.baijiayun.liveuibase.utils.showBonusPointsTab
import com.baijiayun.liveuibase.widgets.popupwindow.BaseAutoArrangePopupWindow
import com.baijiayun.liveuibase.widgets.popupwindow.BaseSelectWindow
import com.google.android.material.tabs.TabLayout
import io.reactivex.android.schedulers.AndroidSchedulers

/**
 * Created by pengwenjian on 2021/7/22
 * Describe: 积分window
 * 设计稿：https://app.mockplus.cn/app/rJRIMo1lw2/specs/design/ESMGFEQGHgNv
 * 积分规则：https://app.mockplus.cn/app/aHwVIQ37dp/specs/design/It0h2d7OjGWN3
 */
class BonusPointsWindow(context: Context) : BaseWindow(context) {
    private val viewPager by lazy {
        view.findViewById<ViewPager>(R.id.bonus_points_viewpager)
    }
    private val tabLayout by lazy {
        view.findViewById<TabLayout>(R.id.bonus_points_tab)
    }
    private val helpList by lazy {
        val list = ArrayList<String>()
        list.add(getString(R.string.base_bouns_points_help_tip_1))
        list.add(getString(R.string.base_bouns_points_help_tip_2))
        list.add(getString(R.string.base_bouns_points_help_tip_3))
        list.add(getString(R.string.base_bouns_points_help_tip_4))
        list.add(getString(R.string.base_bouns_points_help_tip_5))
        list
    }
    private var allUserFragment: BonusPointsFragment? = null
    private var groupRankFragment: BonusPointsFragment? = null
    private var remainTv: TextView? = null
    private var helpIv: ImageView? = null
    private var tabHelpIv: ImageView? = null
    private var selectIndex = -1
    var closeListener: View.OnClickListener? = null

    override fun onCreateView(context: Context?): View {
        val view = View.inflate(context, R.layout.uibase_window_bonus_points, null)
        view.background = ThemeDataUtil.getCommonWindowBg(context)
        allowTouch = false
        return view
    }

    init {
        initView()
        subscribe()
    }

    private fun initView() {
        if (context !is FragmentActivity) {
            return
        }
        val isAdmin = routerListener.getLiveRoom()?.isTeacherOrAssistant == true
                || routerListener.getLiveRoom()?.isGroupTeacherOrAssistant == true
        val titleTv = view.findViewById<TextView>(R.id.title_tv)
        val selectContainer = view.findViewById<View>(R.id.select_ll_container)
        val selectTopArrowIv = view.findViewById<ImageView>(R.id.select_top_arrow_iv)
        val rankSelectTopList =
            context.resources.getStringArray(R.array.base_rank_select_top).toList()
        val selectTopTv = view.findViewById<TextView>(R.id.select_top_tv)
        val bonusPointRankDescContainer = view.findViewById<View>(R.id.points_rank_desc_container)
        helpIv = view.findViewById(R.id.bonus_points_help_iv)
        tabHelpIv = view.findViewById(R.id.bonus_points_tab_help_iv)
        val bonusPointsIv = view.findViewById<View>(R.id.bonus_points_iv)
        val bonusPointsMyTv = view.findViewById<TextView>(R.id.bonus_points_my_tv)
        val bonusPointsTv = view.findViewById<TextView>(R.id.bonus_points_tv)
        val divTab = view.findViewById<View>(R.id.div_tab)
        val divSubTitle = view.findViewById<View>(R.id.div_subtitle)
        view.findViewById<View>(R.id.bonus_points_close_iv)
            .setOnClickListener {
                closeListener?.onClick(it)
            }
        if (isAdmin) {
            titleTv.text = getString(R.string.base_bonus_points_rank)
            view.findViewById<View>(R.id.bottom_container).visibility = View.VISIBLE
        } else {
            titleTv.text = getString(R.string.base_my_bonus_points)
            view.findViewById<View>(R.id.bottom_container).visibility = View.GONE
            helpIv?.visibility = View.GONE
            tabHelpIv?.visibility = View.GONE
        }
        helpIv?.setOnClickListener {
            showBonusPointsHelpPopupWindow()
        }
        tabHelpIv?.setOnClickListener {
            showBonusPointsHelpPopupWindow()
        }
        selectTopTv.text = rankSelectTopList[1]
        remainTv = view.findViewById(R.id.remain_tv)
        remainTv?.text = getString(
            R.string.base_bonus_points_ramain,
            getString(R.string.base_bonus_points_endless)
        )
        val showTab = showBonusPointsTab(routerListener.getLiveRoom())
        if (showTab) {
            allUserFragment = BonusPointsFragment(isAdmin)
            groupRankFragment = BonusPointsFragment(isAdmin)
            tabLayout.visibility = View.VISIBLE
            if (isAdmin) {
                bonusPointRankDescContainer.visibility = View.GONE
                divSubTitle.visibility = View.GONE
                helpIv?.visibility = View.GONE
                tabHelpIv?.visibility = View.VISIBLE
            } else {
                bonusPointRankDescContainer.visibility = View.VISIBLE
                bonusPointsMyTv.text = getString(R.string.base_my_rank)
                bonusPointsTv.text = getString(R.string.base_bonus_points)
            }
        } else {
            allUserFragment = BonusPointsFragment(isAdmin)
            tabLayout.visibility = View.GONE
            divTab.visibility = View.GONE
            bonusPointRankDescContainer.visibility = View.VISIBLE
            if (isAdmin) {
                bonusPointsIv.visibility = View.GONE
                bonusPointsMyTv.text = getString(R.string.base_rank)
                bonusPointsMyTv.typeface = Typeface.DEFAULT_BOLD
                bonusPointsMyTv.setTextColor(
                    ThemeDataUtil.getColorFromThemeConfigByAttrId(
                        context,
                        R.attr.base_theme_window_main_text_color
                    )
                )
                helpIv?.visibility = View.VISIBLE
                tabHelpIv?.visibility = View.GONE
            } else {
                bonusPointsMyTv.text = getString(R.string.base_my_rank)
            }
        }
        val count = if (showTab) 2 else 1
        viewPager.adapter = object : FragmentStatePagerAdapter(
            (context as FragmentActivity).supportFragmentManager,
            BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getCount() = count

            override fun getItem(position: Int): Fragment =
                if (position == 0) allUserFragment!! else groupRankFragment!!
        }
        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                // do nothing
            }

            override fun onPageSelected(position: Int) {
                if (!isAdmin) {
                    if (position == 0) {
                        bonusPointsMyTv.text = getString(R.string.base_my_rank)
                        bonusPointsTv.text = getString(R.string.base_bonus_points)
                    } else {
                        bonusPointsMyTv.text = getString(R.string.base_my_group_rank)
                        bonusPointsTv.text = getString(R.string.base_bonus_points_group_total)
                    }
                } else {
                    selectContainer.visibility = if (position == 0) View.VISIBLE else View.GONE
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                // do nothing
            }
        })
        tabLayout.setupWithViewPager(viewPager)
        val normalDrawable = DrawableBuilder()
            .rectangle()
            .cornerRadii(
                com.baijiayun.livecore.utils.DisplayUtils.dip2px(context, 2f),
                com.baijiayun.livecore.utils.DisplayUtils.dip2px(context, 2f),
                0,
                0
            )
            .strokeWidth(DisplayUtils.dip2px(context, 0.5f))
            .strokeColor(ContextCompat.getColor(context, R.color.base_bg_stroke))
            .build()
        val selectedDrawable = DrawableBuilder()
            .rectangle()
            .cornerRadii(
                com.baijiayun.livecore.utils.DisplayUtils.dip2px(context, 2f),
                com.baijiayun.livecore.utils.DisplayUtils.dip2px(context, 2f),
                0,
                0
            )
            .solidColor(
                ThemeDataUtil.getColorFromThemeConfigByAttrId(
                    context,
                    R.attr.base_theme_live_product_color
                )
            )
            .build()
        val tabTextColor = DisplayUtils.getColorStateList(
            ThemeDataUtil.getColorFromThemeConfigByAttrId(
                context, R.attr.base_theme_dialog_positive_text_color
            ),
            ThemeDataUtil.getColorFromThemeConfigByAttrId(
                context, R.attr.base_theme_window_main_text_color
            ),
            BaseUIConstant.ResStateType.selected
        )
        val allUserTab = tabLayout.getTabAt(0)
        var groupRankTab: TabLayout.Tab? = null
        if (count == 2) {
            groupRankTab = tabLayout.getTabAt(1)
        }
        allUserTab?.run {
            setCustomView(R.layout.uibase_custom_tab_item)
            val tabTv = customView?.findViewById<TextView>(R.id.tab_tv)
            tabTv?.text =
                if (isAdmin) getString(R.string.base_all_user) else getString(R.string.base_my)
            tabTv?.setTextColor(tabTextColor)
            tabTv?.background = StateListDrawableBuilder()
                .normal(normalDrawable)
                .selected(selectedDrawable)
                .build()
            select()
        }
        groupRankTab?.run {
            setCustomView(R.layout.uibase_custom_tab_item)
            val tabTv = customView?.findViewById<TextView>(R.id.tab_tv)
            tabTv?.text =
                if (isAdmin) getString(R.string.base_group_rank) else getString(R.string.base_my_group)
            tabTv?.setTextColor(tabTextColor)
            tabTv?.background = StateListDrawableBuilder()
                .normal(normalDrawable)
                .selected(selectedDrawable)
                .build()
        }
        selectContainer.background = DrawableBuilder()
            .solidColor(ContextCompat.getColor(context, R.color.base_main_color_layer_10))
            .cornerRadius(context.resources.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
            .build()
        selectContainer.setOnClickListener {
            val window = BaseSelectWindow(context, rankSelectTopList, selectIndex)
            window.itemClickListener = object : BaseSelectWindow.OnItemClickListener {
                override fun onItemClick(view: View, position: Int) {
                    if (selectIndex != position) {
                        selectIndex = position
                        selectTopTv.text = rankSelectTopList[position]
                        routerListener.getLiveRoom()?.toolBoxVM?.requestBonusPointsRankList(
                            LPConstants.BonusPointType.TYPE_ALL, when (position) {
                                1 -> 10
                                2 -> 20
                                3 -> 100
                                else -> 5
                            }
                        )
                    }
                    window.dismiss()
                }
            }
            window.setOnDismissListener {
                selectTopArrowIv.setImageResource(R.drawable.base_ic_baseline_keyboard_arrow_down)
            }
            window.show(it)
            selectTopArrowIv.setImageResource(R.drawable.base_ic_baseline_keyboard_arrow_up)
        }
    }

    private fun showBonusPointsHelpPopupWindow() {
        val helpWindow = BaseSelectWindow(context,helpList,isRead = true)
        helpWindow.setOnDismissListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                tabHelpIv?.imageTintList = ColorStateList.valueOf(
                    ContextCompat.getColor(context,R.color.base_local_icon_color_normal)
                )
                helpIv?.imageTintList = ColorStateList.valueOf(
                    ContextCompat.getColor(context,R.color.base_local_icon_color_normal)
                )
            }
        }
        //这里的调整是为了让window出来在icon下方
        // 是根据显示效果来的，这里具体为什么偏移这么多原因不明
        helpWindow.initCustomOffset(-50, -8)
        if (showBonusPointsTab(routerListener.getLiveRoom())) {
            helpWindow.show(tabHelpIv,BaseAutoArrangePopupWindow.RIGHT_BOTTOM)
        } else {
            helpWindow.show(helpIv,BaseAutoArrangePopupWindow.RIGHT_BOTTOM)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            helpIv?.imageTintList = ColorStateList.valueOf(
                ThemeDataUtil.getColorFromThemeConfigByAttrId(
                    context,
                    R.attr.base_theme_live_product_color
                )
            )
            tabHelpIv?.imageTintList = ColorStateList.valueOf(
                ThemeDataUtil.getColorFromThemeConfigByAttrId(
                    context,
                    R.attr.base_theme_live_product_color
                )
            )
        }
    }

    private fun subscribe() {
        routerListener.getLiveRoom()?.run {
            compositeDisposable.addAll(toolBoxVM.observableOfBonusPointsRankList
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (it.type == LPConstants.BonusPointType.TYPE_ALL
                        || it.type == LPConstants.BonusPointType.TYPE_MY

                    ) {
                        allUserFragment?.bonusPointsRankList = it
                        remainTv?.text =
                            getString(
                                R.string.base_bonus_points_ramain,
                                it.remainPoints.toString()
                            )
                    } else {
                        groupRankFragment?.bonusPointsRankList = it
                    }
                })
            toolBoxVM.requestBonusPointsRankList(
                if (isTeacherOrAssistant || isGroupTeacherOrAssistant) {
                    LPConstants.BonusPointType.TYPE_ALL
                } else {
                    LPConstants.BonusPointType.TYPE_MY
                }, 10
            )
            if (showBonusPointsTab(this)) {
                toolBoxVM.requestBonusPointsRankList(
                    if (isTeacherOrAssistant || isGroupTeacherOrAssistant) {
                        LPConstants.BonusPointType.TYPE_GROUP
                    } else {
                        LPConstants.BonusPointType.TYPE_MY_GROUP
                    }, 100
                )
            }
            selectIndex = 1
        }
    }
}
